package by.demchenko.sample.webapp.page.home.teachers;

import by.demchenko.sample.datamodel.Result;
import by.demchenko.sample.datamodel.Result_;
import by.demchenko.sample.datamodel.Schedule;
import by.demchenko.sample.services.ResultService;
import by.demchenko.sample.webapp.page.home.BaseLayout;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;
import java.util.Iterator;


public class GradesSetPage extends BaseLayout {

    @Inject
    ResultService resultService;

    private Schedule schedule;

    private DataView<Result> dataView;

    public GradesSetPage(Schedule schedule) {

        this.schedule = schedule;

        ResultDataProvider resultDataProvider = new ResultDataProvider();

        Form<Result> form = new Form<Result>("form") {
            @Override
            protected void onValidate() {
                super.onValidate();
                visitChildren(FormComponent.class, new IVisitor<FormComponent, Void>() {
                    @Override
                    public void component(FormComponent component, IVisit<Void> iVisit) {
                        component.processInput();
                        if (component.hasErrorMessage()) {
                            for (FeedbackMessage message : component.getFeedbackMessages()) {
                                if (message.isError()) {
                                    error(message.getMessage());
                                }
                            }
                        }
                    }
                });
            }
        };

        add(form);

        add(new FeedbackPanel("feedback")

        );

        dataView = new DataView<Result>("studentsList", resultDataProvider)

        {
            @Override
            protected void populateItem(Item<Result> item) {
                final Result result = item.getModelObject();
                item.add(new Label("student", result.getStudent().getFullName(getSession().getLocale())));
                item.add(new Label("faculty", result.getStudent().getFaculty().getName()));
                final TextField<String> tfGrade = new TextField<>("grade", new PropertyModel<>(result, "grade"));
                tfGrade.add(new PropertyValidator<Integer>());
                tfGrade.setLabel(new ResourceModel("result.grade"));
                item.add(tfGrade);
            }
        };

        form.add(dataView);

        form.add(new SubmitLink("sumbit-link") {
                     @Override
                     public void onSubmit() {
                         super.onSubmit();

                         Iterator<Item<Result>> a = dataView.getItems();
                         while (a.hasNext()) {
                             Result res = a.next().getModelObject();
                             resultService.saveOrUpdate(res);
                         }

                         TeacherCoursesPage page = new TeacherCoursesPage();
                         setResponsePage(page);
                     }

                     @Override
                     public void onError() {
                         super.onError();
                         //error("error");
                     }
                 }

        );

        form.add(new Link<Void>("back-link")
                 {
                     @Override
                     public void onClick() {
                         setResponsePage(new TeacherCoursesPage());
                     }
                 }

        );

    }

    private class ResultDataProvider extends SortableDataProvider<Result, SingularAttribute<Result, ?>> {

        public ResultDataProvider() {
            super();
            setSort(Result_.student, SortOrder.ASCENDING);
        }

        @Override
        public Iterator<? extends Result> iterator(long l, long l1) {
            SingularAttribute<Result, ?> sortParam = getSort().getProperty();
            SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
            boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
            return resultService.getGradesByCourse(schedule).iterator();
        }

        @Override
        public long size() {
            return resultService.getCount();
        }

        @Override
        public IModel<Result> model(Result result) {
            return new CompoundPropertyModel<>(result);
        }
    }
}
